
#ifndef _NEBULA_SDK__TASK_PROCESSOR_H__INCLUDED_
#	error Should not include TaskProcessorImpl.h directly, include TaskProcessor.h instead
#endif

#include "Utility/ThreadPool.h"

namespace nebula { namespace sdk {

template <typename service_type>
class TaskProcessorImpl : public utility::ThreadPool
{
public:
	typedef typename TaskProcessor<service_type>::task_processor task_processor;

public:
	TaskProcessorImpl(const char* name):
			ThreadPool(name),
			ptr_task_queue(NULL),
			ptr_service(NULL),
			task_proc(NULL)
	{
	}
	~TaskProcessorImpl(){}

public:
	virtual NEBULA_ERROR_CODE start(
			service_type *service,
			task_processor proc,
			ITodoTaskQueue *queue,
			unsigned int min_thread_count,
			unsigned int max_thread_count)
	{
		ptr_task_queue = queue;
		ptr_service = service;
		task_proc = proc;
		return ThreadPool::start(min_thread_count, max_thread_count);
	}

protected:
	virtual void worker(ThreadContext* context)
	{
		if(! context)
			return;
		while (!context->quit.is_set())
		{
			ITask* ptr_task_data = ptr_task_queue->GetTask(true, 10);
			if (NULL != ptr_task_data)
			{
				context->status = THR_STATUS_BUSY;
				(ptr_service->*(task_proc))( std::auto_ptr<ITask>(ptr_task_data) );
				ptr_task_queue->TaskDone();
				context->status = THR_STATUS_IDLE;
			}
		}
		context->status = THR_STATUS_TERMINATED;
	}

private:
	ITodoTaskQueue* ptr_task_queue;
	service_type* ptr_service;
	task_processor task_proc;
};

}}
